<template>
  <wd-popup custom-class="popup-custom" v-model="show" custom-style="border-radius:32rpx;">
    <wd-card title="对公转账以及上传转账截图">
      <view class="plyment-upload">
        <view class="row">对公转账银行（可长按复制）</view>
        <view class="row" @click="copyBankAccount">1234567890123456</view>
        <view>
          <wd-img
            width="100"
            height="100"
            :round="true"
            :radius="50"
            :src="imageUrl"
            v-if="imageUrl"
          ></wd-img>
        </view>
        <view><button class="upload-btn" @click="uploadImage">上传转账截图</button></view>
      </view>
      <template #footer>
        <button class="back-btn" @click="goBack">返回</button>
      </template>
    </wd-card>
  </wd-popup>
</template>

<script setup>
import { ref } from 'vue'
import useUpload from '@/hooks/useUpload'
import { getEnvBaseUrl } from '@/utils/index'
const show = ref(false)
let stopWatch = null
const imageUrl = ref('')
const emit = defineEmits(['upload'])
const api = {
  uploadUrl: `${getEnvBaseUrl()}/sys/common/upload`,
}

const open = () => {
  show.value = true
}

const copyBankAccount = () => {
  uni.setClipboardData({
    data: '1234567890123456',
    success: () => {
      uni.showToast({
        title: '银行账号已复制',
        icon: 'success',
      })
    },
  })
}

const uploadImage = () => {
  const { loading, data, error, run } = useUpload({ name: 'file' }, { url: api.uploadUrl })
  if (stopWatch) stopWatch()
  run()
  stopWatch = watch(
    () => [loading.value, error.value, data.value],
    ([loading, err, data], oldValue) => {
      if (loading === false) {
        if (err) {
          toast.warning('修改失败')
          uni.hideLoading()
        } else {
          if (data) {
            console.log('data', data)
            if (data.success) {
              imageUrl.value = data.message
              emit('upload', data.message)
              show.value = false
            } else {
              toast.warning('上传失败')
            }
          }
        }
      }
    },
  )
}

onBeforeUnmount(() => {
  stopWatch?.()
})

const goBack = () => {
  show.value = false
}
defineExpose({
  open,
})
</script>

<style scoped>
:deep(.popup-custom) {
  width: 90%;
}
:deep(.wd-card__title) {
  text-align: center;
}
.plyment-upload {
  text-align: center;
  color: #000;
}
.plyment-upload .row {
  margin: 20rpx 0;
  font-size: 20px;
}
</style>
